package com.zbh.uexam.utility;

import lombok.extern.slf4j.Slf4j;
import org.modelmapper.internal.util.Lists;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author zhoubh
 * @Date 2021/4/24 17:34
 * @Version 1.0
 * @description: 权重工具类
 */
@Slf4j
public class WeightUtil {

    /**
     * 根据难度获得不同难度权重列表
     * @param difficult 难度，1-5
     * @return 权重列表
     */
    public static List<Integer> getDifficultWeightList(int difficult) {
        // 表示下标
        difficult -= 1;
        List<Integer> difficultWeightList = new ArrayList<>(Arrays.asList(0,0,0,0,0));
        int l = difficult - 1, r = difficult + 1;

        // 系数
        int curCoefficient = (int) Math.pow(2, Math.max(difficult, 4 - difficult));

        int totalCoefficient = curCoefficient;

        difficultWeightList.set(difficult, curCoefficient);
        curCoefficient /= 2;
        while ( l >= 0 || r < 5) {
            if ( l >= 0 ) {
                difficultWeightList.set(l, curCoefficient);
                totalCoefficient += curCoefficient;
            }
            if (r < 5) {
                difficultWeightList.set(r, curCoefficient);
                totalCoefficient += curCoefficient;
            }
            l--;
            r++;
            curCoefficient /= 2;
        }

        return difficultWeightList;
    }

    /**
     * 随机通过权重获得难度
     * @param difficultWeightList 权重列表
     * @return 难度
     */
    public static int getDifficultRandomByWeight(List<Integer> difficultWeightList) {
        log.info("getDifficultRandomByWeight:{}", JsonUtil.toJsonStr(difficultWeightList));
        int sum = difficultWeightList.stream().mapToInt(x -> x).sum();
        Random rnd = new Random();
        int n = rnd.nextInt(sum);
        int partSum = 0;
        for (int i = 0; i < difficultWeightList.size(); i++) {
            partSum += difficultWeightList.get(i);
            if (n < partSum) {
                // 获得难度
                return i + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        List<Integer> difficultWeightList = getDifficultWeightList(3);
        System.out.println(getDifficultRandomByWeight(difficultWeightList));
    }
}
